<template>
  <view class="container">
    <!-- 遮罩层弹窗 -->
    <view v-if="showNoticeModal" class="mask">
      <view class="notice-modal">
        <view class="notice-header">廉洁提醒</view>
        <view class="notice-content">
            <text>为营造公平、公正、透明的营商环境，防范商业贿赂风险，请您在业务办理过程中严格遵守以下廉洁规定：\n\n一、禁止行为\n1. 严禁向我司工作人员赠送礼品、礼金、有价证券等财物；\n2. 严禁安排或接受可能影响公正办事的宴请、旅游、娱乐等活动；\n3. 严禁以任何名义向我司工作人员提供回扣、佣金、好处费等；\n4. 严禁以不正当手段获取我司商业秘密或内部信息；\n5. 严禁通过任何方式干扰我司正常工作秩序。\n\n二、监督举报\n如发现我司工作人员存在违反廉洁纪律的行为，请您及时举报：\n举报电话：010-XXXXXXX\n举报邮箱：lianzheng@company.com\n\n三、法律责任\n对于违反上述规定的，我司将依法依规严肃处理，涉嫌违法犯罪的将移交司法机关处理。\n\n感谢您的理解与配合！</text>
        </view>
        <view class="notice-footer">
          <button class="smart-form-submit-btn" type="primary"  @click="confirmNotice">我已知晓</button>
        </view>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="smart-form" v-show="!showNoticeModal">
      <uni-forms ref="formRef" :label-width="100" :modelValue="form" label-position="left" :rules="rules">
        <view class="smart-form-group">
          <view class="smart-form-group-content">
            <uni-forms-item class="smart-form-item" label="企业名称：" name="enterpriseName" required>
              <uni-easyinput type="input" trim="all" v-model="form.enterpriseName" placeholder="请输入" class="rounded-input" />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="预约类型：" name="reservationType" required>
              <uni-data-select v-model="form.reservationType" :localdata="reservationTypeList" @change="changeReservationType" class="rounded-input"/>
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="预约姓名：" name="reservationUser" required>
              <uni-easyinput type="input" trim="all" v-model="form.reservationUser" placeholder="请输入" class="rounded-input"/>
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="预约电话：" name="reservationPhone" required>
              <uni-easyinput type="input" trim="all" v-model="form.reservationPhone" placeholder="请输入" class="rounded-input"/>
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="预约时间：" name="reservationTime" required>
              <uni-datetime-picker type="datetime" v-model="form.reservationTime" class="rounded-input"/>
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="附件1：" name="reservationFile1" required>
                <uni-file-picker
                limit="1"
                @delete="onDeleteReservationFile1File"
                v-model="reservationFile1"
                @select="onSelectReservationFile1File"
                file-mediatype="all"
                class="rounded-input"
              />
            </uni-forms-item>
            <uni-forms-item class="smart-form-item" label="附件2：" name="reservationFile2" required>
              <uni-file-picker
                limit="1"
                @delete="onDeleteReservationFile2File"
                v-model="reservationFile2"
                @select="onSelectReservationFile2File"
                file-mediatype="all"
                class="rounded-input"
              />
            </uni-forms-item>
          </view>
        </view>
      </uni-forms>

      <view class="smart-form-submit fixed-bottom-button">
        <button class="smart-form-submit-btn" type="default" @click="cancel">取消</button>
        <button class="smart-form-submit-btn" type="primary" @click="submit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
    /* global uni */
    import {onMounted, reactive, ref} from 'vue';
    import {reservationApi} from '@/api/business/oa/reservation-api';
    import {smartSentry} from '@/lib/smart-sentry';
    import {SmartLoading, SmartToast} from '@/lib/smart-support';
    import {fileApi} from '@/api/support/file-api';
    import {FILE_FOLDER_TYPE_ENUM} from '@/constants/support/file-const';
    import {dictApi} from "@/api/support/dict-api";
    import _ from 'lodash';

    // --------------------- 表单 ---------------------

    const showNoticeModal = ref(true); // 控制遮罩层显示

    function confirmNotice() {
      showNoticeModal.value = false;
    }

    const defaultFormData = {
      enterpriseName: '',
      reservationType: '',
      reservationUser: '',
      reservationPhone: '',
      reservationTime: '',
      reservationFile1: [],
      reservationFile2: []
    };
    let form = reactive({...defaultFormData});

    const reservationTypeList = ref([]);

    async function queryDictDataListByCode() {
      let res = await dictApi.getDictDataListByCode("SUPPLIER_TYPE");
      reservationTypeList.value = res.data.map((e) => Object.assign({}, {text: e.dataLabel, value: e.dataValue}));
    }

    onMounted(() => {
      queryDictDataListByCode();
    });

    function changeReservationType(e) {
      form.dataValue = e;
      form.dataLabel = _.find(reservationTypeList.value, {value: form.dataValue}).text;
    }

    const reservationFile1 = ref([]);
    const reservationFile2 = ref([]);

    const rules = {
      enterpriseName: {
        rules: [{required: true, errorMessage: '请输入'}],
      },
      reservationType: {
        rules: [{required: true, errorMessage: '请选择'}]
      },
      reservationUser: {
        rules: [{required: true, errorMessage: '请输入'}],
      },
      reservationPhone: {
        rules: [{required: true, errorMessage: '请输入'}],
      },
      reservationTime: {
        rules: [{required: true, errorMessage: '请选择'}],
      },
      reservationFile1: {
        rules: [{required: true, errorMessage: '请上传'}],
      },
      reservationFile2: {
        rules: [{required: true, errorMessage: '请上传'}],
      }
    };

    function onPlaceChange(value, text) {
      form.placeName = text;
    }


    // --------------------- 文件 ---------------------
    function onSelectReservationFile1File(param) {
      let tempFilePaths = param.tempFilePaths;
      for (const tempFilePath of tempFilePaths) {
        upload(tempFilePath, 'reservationFile1');
      }
    }

    function onSelectReservationFile2File(param) {
      let tempFilePaths = param.tempFilePaths;
      for (const tempFilePath of tempFilePaths) {
        upload(tempFilePath, 'reservationFile2');
      }
    }

    async function upload(tempFilePath, key) {
      try {
        SmartLoading.show();
        let res = await fileApi.upload(tempFilePath, FILE_FOLDER_TYPE_ENUM.FEEDBACK.value);
        res.data.tempFilePath = tempFilePath;
        form[key].push(res.data);
      } catch (e) {
        smartSentry.captureError(e);
      } finally {
        SmartLoading.hide();
      }
    }

    function onDeleteReservationFile1File(param) {
      if (!param.tempFilePath) {
        return;
      }
      _.remove(form.reservationFile1, (e) => e.tempFilePath === param.tempFilePath);
    }

    function onDeleteReservationFile2File(param) {
      if (!param.tempFilePath) {
        return;
      }
      _.remove(form.reservationFile2, (e) => e.tempFilePath === param.tempFilePath);
    }

    // ----------------------- 表单操作 ------------------------

    const formRef = ref();

    // 取消
    function cancel() {
      uni.navigateBack();
    }

    // 确定
    function submit() {
      formRef.value
          .validate()
          .then(async () => {
            SmartLoading.show();
            try {
              await reservationApi.create(form);
              SmartToast.success('提交成功');
              uni.navigateBack();
            } catch (error) {
              smartSentry.captureError(error);
            } finally {
              SmartLoading.hide();
            }
          })
          .catch((error) => {
            console.log('error', error);
            // SmartToast.toast('参数验证错误，请仔细填写表单数据!');
          });
    }
</script>
<style lang="scss" scoped>
@import '@/theme/reservation.scss';
</style>
